package com.hk.employeemanagementsystem.web.controller;

import com.hk.employeemanagementsystem.entity.UserEntity;
import com.hk.employeemanagementsystem.service.impl.SecurityService;
import com.hk.employeemanagementsystem.util.jwt.JwtTokenUtil;
import com.hk.employeemanagementsystem.util.web.WebCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by 何坤
 * @Classname LoginController
 * @Description TODO
 * @Date 2019/12/5 15:12
 */
@RestController
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SecurityService securityService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping(value = "/login")
    public Map<String, Object> login(HttpServletRequest request){
        Map<String, Object> tips = new HashMap<>();
        try {
            String username = request.getParameter("phone");
            String password = request.getParameter("password");
            logger.info("{} --- {}", username, password);
            UserEntity user = (UserEntity) securityService.loadUserByUsername(username);
            String token = jwtTokenUtil.generateToken(user);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_OPERATE);
            tips.put("token", token);
            tips.put("data", user);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
        }
        return tips;
    }
}
